﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;

namespace Microsoft.Services.Clab.UI.Mvvmc
{
    public class KeyValue : DependencyObject, INotifyPropertyChanged
    {
        public KeyValue()
        {

        }

        public KeyValue(string name, object value)
        {
            this.Name = name;
            this.Value = value;
        }

        #region Name Dependency Property

        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }

        public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(KeyValue), new PropertyMetadata(null, OnPropertyChanged));

        #endregion

        #region Value Dependency Property

        public object Value
        {
            get { return (object)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(object), typeof(KeyValue), new PropertyMetadata(null, OnPropertyChanged));

        #endregion

        public T GetValue<T>()
        {
            if (typeof(T).IsInstanceOfType(this.Value))
            {
                return (T)this.Value;
            }
            else
            {
                return (T)Convert.ChangeType(this.Value, typeof(T), Thread.CurrentThread.CurrentCulture);
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }

        #endregion

        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as KeyValue).OnPropertyChanged(new PropertyChangedEventArgs(e.Property.Name));
        }
    }
}
